package nju.jun.reader.tieba.data;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import nju.jun.reader.tieba.model.TiebaNovel;
import nju.jun.reader.tieba.model.TiebaNovelChapter;

public class TiebaNovelWriter implements TiebaNovelContentListener {

	@Override
	public void onContentReady(TiebaNovelChapter chapter) {
		
		TiebaNovel novel = chapter.getNovel();
		if (novel == null) {
			System.err.println("Parameter error since there is no novel instance.");
			return;
		}
		
		// TODO: write content to file
		File dir = new File(novel.getStorageDirectory());
		if (!dir.exists()) {
			if (!dir.mkdirs()) {
				System.err.println("Cannot create storage directory: " + dir.getPath());
			}
		}
		
		File volume = new File(chapter.getVolumeDirStr());
		if (!volume.exists()) {
			if (!volume.mkdir()) {
				System.err.println("Cannot create volume directory: " + volume.getPath());
			}
		}
		
		File newFile = new File(chapter.getChapterFileStr());
//		String fName = chapter.getChapterNumber() + "_" + chapter.getChapterName();
//		File newFile = new File(dir.getAbsolutePath() + "/" + fName);
		if (newFile.exists()) {
			newFile.delete();
		}
		try {
			newFile.createNewFile();
			PrintWriter pw = new PrintWriter(newFile);
			pw.append(chapter.getContent());
			pw.flush();
			pw.close();
		} catch (IOException e) {
//			System.err.println("Cannot create file to write this chapter: " + fName);
			System.err.println("Cannot create file to write this chapter: " + newFile.getPath());
		}
	}

}
